//必须带done回调 执行完成调用
// 获取表格编辑状态下值修改后的数据
import { gp } from '@vui'
import { translateTitle } from '@/utils/i18n'

export default function getRecordset({ vm, action, done, eventName }) {
  let tableId = action.extension.tableId.value && action.extension.tableId.value[0]
  // console.log('_table', tableId)
  if (tableId && vm.vuiComponents) {
    let _table = vm.vuiComponents[tableId]
    if (_table) {
      // 先退出表格编辑模式
      _table.ref.clearEdit()
      const { insertRecords, removeRecords, updateRecords } = _table.ref.getRecordset()
      if (insertRecords.length <= 0 && removeRecords.length <= 0 && updateRecords.length <= 0) {
        gp.$baseMessage(translateTitle('Ve.eventTask.数据未改动'), 'warning')
        // 修改任务队列执行状态，防止下一次事件被拦截
        vm[`${eventName}IsRunning`] = false
        return
      }
      const fullValidEvent = async () => {
        const $table = _table.ref
        const editRows = $table.getUpdateRecords()
        const errMap = await $table.fullValidate(editRows)
        if (errMap) {
          const msgList = []
          Object.values(errMap).forEach((errList) => {
            errList.forEach((params) => {
              const { rowIndex, column, rules } = params
              rules.forEach((rule) => {
                msgList.push(
                  `${translateTitle('Ve.eventTask.第')} ${rowIndex + 1} ${translateTitle('Ve.eventTask.行')} ${column.title} ${translateTitle(
                    'Ve.eventTask.校验错误'
                  )}：${rule.message}`
                )
              })
            })
          })
          let msgHtml = ``
          msgList.forEach((msg) => {
            msgHtml += `${msg}<br>`
          })
          gp.$baseMessage(msgHtml, 'warning', '', true)
          return false
        } else {
          if (_table.self.getInfo?.extension?.clickEdit?.value?.tipOpen) {
            gp.$baseMessage(`${translateTitle('Ve.eventTask.校验成功')}`, 'success')
          }
          return true
        }
      }
      fullValidEvent().then((status) => {
        if (status) {
          // 存储动作数据
          vm.$store.dispatch('actionDatas/setActionsData', {
            moduleId: vm.info._id,
            actionId: action._id,
            actionData: updateRecords,
          })
          done(null, updateRecords)
        }
      })
    } else {
      console.log('获取表格编辑状态下值修改后的数据-没有找到表格')
      done(null, {})
    }
  } else {
    console.log('获取表格编辑状态下值修改后的数据-未选择表格')
    done(null, {})
  }
}
